import { BaseCommand, Icon, log, useCommandManager } from '@amcax/base';
import { Tooltip } from 'antd';
import i18n from 'i18next';
import { StyledButton } from '../styled';
import { useEffect, useState } from 'react';

interface IProps {
  activated?: boolean;
  cmd: BaseCommand;
  onCmdInvoked?: (cmd: BaseCommand) => void;
  onCmdInvokFinished?: (cmd: BaseCommand) => void;
  className?: string;
}

export const ToolButton = ({
  onCmdInvoked,
  onCmdInvokFinished,
  activated,
  cmd,
  className,
}: IProps) => {
  const { invokeCmd } = useCommandManager();
  const [disabled, setDisabled] = useState(!!cmd.initialDisabled);
  useEffect(() => {
    log('ToolButton Init', cmd);
    cmd.subscribeDisabled?.(setDisabled);
  }, []);

  return (
    <Tooltip
      title={cmd.label ? i18n.t(cmd.label) : undefined}
      placement='bottom'>
      <StyledButton
        onClick={() => {
          invokeCmd(cmd, null, null, () => onCmdInvokFinished(cmd));
          onCmdInvoked?.(cmd);
        }}
        className={className}
        activated={activated}
        icon={
          cmd.icon && (
            <Icon
              name={cmd.icon}
              style={{
                fontSize: '18px',
                opacity: disabled ? 0.3 : 1,
              }}
            />
          )
        }></StyledButton>
    </Tooltip>
  );
};
